package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.ExceptionCatch.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.1判断手机号密码是否为空
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            //1.2根据手机号查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }
            //1.2对比密码和数据库中的密码是否一致
            String inputPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!inputPwd.equals(apUser.getPassword())){
                 CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //1.3办法token
            String token = AppJwtUtil.getToken(Long.valueOf((apUser.getId())));
            //1.4 返回结果user token
            Map result = new HashMap<>();
            result.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            result.put("user",apUser);
            return  ResponseResult.okResult(result);
        }else {
            //1使用设备id登入
            //2判断id是否为空
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
                //颁发token
            //3办法token
            String token = AppJwtUtil.getToken(0L);
            Map result = new HashMap<>();
            result.put("token",token);
            return  ResponseResult.okResult(result);

        }









    }
}
